package net.wanho.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.wanho.mapper.ProductMapper;
import net.wanho.po.ProductType;
import net.wanho.service.ProductTypeService;
import net.wanho.mapper.ProductTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【product_type(商品分类表)】的数据库操作Service实现
* @createDate 2025-04-28 11:41:58
*/
@Service
public class ProductTypeServiceImpl extends ServiceImpl<ProductTypeMapper, ProductType>
    implements ProductTypeService{

    private final ProductTypeMapper productTypeMapper;

    @Autowired
    private ProductMapper productMapper;

    public ProductTypeServiceImpl(ProductTypeMapper productTypeMapper) {
        this.productTypeMapper = productTypeMapper;
    }

    @Override
    public List<ProductType> selectAll() {

        List<ProductType> productTypes = this.list();

        List<ProductType> collect = productTypes.stream()
                .filter(item -> item.getParentId().equals(0))
                .map(item -> {
                    findChildren(item, productTypes);
                    return item;
                }).collect(Collectors.toList());
        return collect;

    }

    @Override
    public Boolean selectByCode(String typeCode) {
        return productTypeMapper.selectByTypeCode(typeCode);
    }

    @Override
    public void deleteById(Integer id) {
        // 若该商品分类下有商品，则不能删除
        if (ObjectUtil.isNotEmpty(productMapper.selectByTypeId(id))) {
            throw new RuntimeException("该商品分类下有商品，不能删除");
        }
        productTypeMapper.deleteById(id);
    }

    private void findChildren(ProductType item, List<ProductType> productTypes) {
        List<ProductType> collect = productTypes.stream()
                .filter(item2 -> item2.getParentId().equals(item.getTypeId()))
                .map(item2 -> {
                    findChildren(item2, productTypes);
                    return item2;
                })
                .collect(Collectors.toList());
        item.setChildProductCategory(collect);
    }
}




